<template>
  <vab-card class="searchfor">
    <template #header>
      <div class="leve2_title">采购基础信息</div>
    </template>
    <el-form
      ref="baseFormRef"
      :model="baseForm"
      label-width="120px"
      v-loading="loading"
      label-position="right"
    >
      <el-row :gutter="24">
        <!-- 左侧 -->
        <el-col :span="12" :xs="12" :sm="12" :md="12" :lg="12" :xl="12">
          <el-col
            v-for="(item, i) in OrderCreateLeft"
            v-bind="colLayout"
            :key="i"
          >
            <!-- 买方 -->
            <el-form-item
              v-if="item.type == 'select_buyer'"
              :label="item.label"
              :prop="item.prop"
              :rules="[
                {
                  required: true,
                  message: `${item.label}不能为空`,
                  trigger: 'blur',
                },
              ]"
            >
              <el-select
                :ref="(el) => (buyNumberRef = el)"
                v-model.trim="baseForm[item.prop]"
                placeholder="请选择"
                class="width_80"
                filterable
                clearable
                @change="
                  (value: any) => {
                    handleVabSelectChange(value, item.prop)
                  }
                "
              >
                <el-option
                  v-for="item in categoryArray"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                ></el-option>
              </el-select>
            </el-form-item>

            <!-- 默认项 -->
            <el-form-item
              v-if="item.type == 'select'"
              :label="item.label"
              :prop="item.prop"
              :rules="[
                {
                  required: true,
                  message: `${item.label}不能为空`,
                  trigger: 'blur',
                },
              ]"
            >
              <VabSelectForm
                class="width_80"
                v-model.trim="baseForm[item.prop]"
                :options="selectOptions(item.prop)"
                @change="
                  (value: any) => {
                    handleVabSelectChange(value, item.prop)
                  }
                "
              />
            </el-form-item>

            <!-- input -->
            <el-form-item
              v-if="item.type == 'input'"
              :label="item.label"
              :prop="item.prop"
              :rules="[
                {
                  required: item.required,
                  message: `${item.label}不能为空`,
                  trigger: 'blur',
                },
              ]"
            >
              <el-input
                clearable
                placeholder="请输入"
                class="width_80 height_auto"
                v-model.trim="baseForm[item.prop]"
              />
            </el-form-item>
            <!-- input -->
            <el-form-item
              v-if="item.type == 'selectCreate'"
              :label="item.label"
              :prop="item.prop"
              :rules="[
                {
                  required: true,
                  message: `${item.label}不能为空`,
                  trigger: 'blur',
                },
              ]"
            >
              <VabSelectCreateForm
                class="width_80"
                v-model.trim="baseForm[item.prop]"
                :options="selectOptions(item.prop)"
                :add-a-pi="'/api/dms/options/create'"
                :addFactor="{
                  level: 2,
                  module: 'transport_type',
                  module_name: '运输方式',
                }"
                @customAdd="handleCustomAdd(item.prop)"
              />
            </el-form-item>
          </el-col>
        </el-col>
        <!--右侧 -->
        <el-col :span="12" :xs="12" :sm="12" :md="12" :lg="12" :xl="12">
          <el-col
            v-for="(item, i) in OrderCreateRight"
            v-bind="colLayout"
            :key="i"
          >
            <!-- 地址识别 -->
            <el-form-item
              v-if="item.type == 'identify'"
              :label="item.label"
              :prop="item.prop"
            >
              <div class="border width_80">
                <el-input
                  class="width_100"
                  :rows="2"
                  v-model="baseForm.pasteAddress"
                  placeholder="粘贴整段文字，自动识别地址、姓名、电话"
                />
                <div class="flex_just_end" style="margin-top: 12px">
                  <el-button
                    size="small"
                    type="primary"
                    @click="handleAddress(baseForm.pasteAddress)"
                  >
                    识别
                  </el-button>
                  <el-button size="small" @click="baseForm.pasteAddress = ''">
                    清空
                  </el-button>
                </div>
              </div>
            </el-form-item>
            <!-- 默认项 -->
            <el-form-item
              v-if="item.type == 'select'"
              :label="item.label"
              :prop="item.prop"
              :rules="[
                {
                  required: true,
                  message: `${item.label}不能为空`,
                  trigger: 'blur',
                },
              ]"
            >
              <VabSelectForm
                class="width_80"
                v-model.trim="baseForm[item.prop]"
              />
            </el-form-item>
            <el-form-item
              v-if="item.type == 'address'"
              :label="item.label"
              prop="shipping_address"
              :rules="[
                {
                  required: true,
                  message: `${item.label}不能为空`,
                  trigger: 'blur',
                },
              ]"
            >
              <el-cascader
                class="width_80"
                v-model="baseForm.shipping_address"
                :options="arrdessOptions"
                :props="{ value: 'name', label: 'name' }"
              />
            </el-form-item>
            <!-- input -->
            <el-form-item
              v-if="item.type == 'input'"
              :label="item.label"
              :prop="item.prop"
              :rules="[
                {
                  required: true,
                  message: `${item.label}不能为空`,
                  trigger: 'blur',
                },
              ]"
            >
              <el-input
                clearable
                placeholder="请输入"
                class="width_80 height_auto"
                v-model.trim="baseForm[item.prop]"
              />
            </el-form-item>
          </el-col>
        </el-col>
      </el-row>
    </el-form>
  </vab-card>
</template>
<script lang="ts" setup>
  defineOptions({
    name: 'Cooperate',
  })
  const props = defineProps(['from_type'])
  /**
   * @import
   */
  import {
    getCustomerCategoryList,
    homeAddressParse,
  } from '~/src/api/dms/home/homeCustomer'
  import {
    OrderCreateLeft,
    OrderCreateRight,
    OtherOutSearchSelect,
  } from '../../components/tools'
  import { getBaseList } from '~/src/api/dms/public'
  import { ElMessageBox } from 'element-plus'
  import { areaOptions } from '~/src/views/corpIndex/means/means'

  /**
   * @var
   */

  const colLayout = {
    xs: 24,
    sm: 24,
    md: 24,
    lg: 24,
    xl: 24,
  }
  // 全局吐司
  const proxy: any = getCurrentInstance()?.proxy
  const userInfo = ref<any>(localStorage.getItem('userInfo'))
  // 地址
  const arrdessOptions = ref<any>([])

  // 买方
  const baseFormRef = ref<any>()
  const buyNumberRef = ref<any>()
  const buyUid = ref<any>('')

  let baseForm = ref<any>({
    shipping_address: '',
  })
  // 筛选项
  const screenOptions = reactive<any>({
    categoryList: [],
  })

  const categoryArray = ref<any[]>([])
  const loading = ref<boolean>(false)

  /**
   * @method
   */
  const emit = defineEmits(['switchBuyer'])

  // 筛选项格式化
  const selectOptions = (value: string) => {
    if (!screenOptions && !value) return
    return OtherOutSearchSelect(value, screenOptions)
  }
  // 地址解析
  const handleAddress = (address = '') => {
    if (!address) {
      proxy.$Message('识别地址不能为空！', 'warning')
      return
    }
    homeAddressParse({ address }).then((res: any) => {
      if (res.code != 200) {
        proxy.$Message('请填写正确地址格式！', 'warning')
        return
      }

      const data = res.data
      const { city, detail, district, mobile, name, province } = data[0]

      baseForm.value.shipping_province = province
      baseForm.value.shipping_city = city
      baseForm.value.shipping_district = district

      baseForm.value.shipping_address = [province, city, district]
      baseForm.value.address = detail
      baseForm.value.shipping_contact = name
      baseForm.value.shipping_tel = mobile
    })
  }

  // 基础信息赋值
  const toBaseFrom = (row: any) => {
    baseForm.value.tax_number = row.tax_register_code
    baseForm.value.invoice_str = row.invoice_title

    baseForm.value.shipping_address = row.shipping_address
      ? row.shipping_address.split(',')
      : []
    baseForm.value.address = row.address
    baseForm.value.shipping_contact = row.shipping_contact
    baseForm.value.shipping_tel = row.shipping_tel
  }

  const handleVabSelectChange = (value: any, prop: any) => {
    if (prop == 'buyer_customer_id') {
      let row: any = null

      categoryArray.value.forEach((item: any) => {
        if (item.uid == value) row = item
      })
      if (buyUid.value && buyUid.value != value) {
        ElMessageBox.confirm('切换买方，会清空采购产品信息，是否确认', '提示', {
          confirmButtonText: '确认',
          cancelButtonText: '取消',
          type: 'warning',
        })
          .then(() => {
            // 清除焦点
            buyNumberRef.value.$refs.reference.blur()
            // 买方id
            baseForm.value.buyer_customer_id = value
            // 判断key
            buyUid.value = value
            // 基础数据赋值
            toBaseFrom(row)
            // 买方number传递
            emit('switchBuyer', row.number, true)
          })
          .catch(() => {
            buyNumberRef.value.$refs.reference.blur()
            baseForm.value.buyer_customer_id = buyUid.value
          })
      } else {
        buyUid.value = value
        toBaseFrom(row)
        emit('switchBuyer', row.number)
      }
    }
  }

  // 获取基础筛选项
  const _GetScreenOptions = async () => {
    const cateRes = await getCustomerCategoryList() //买方
    const transportRes = await getBaseList('transport_type') //运输方式
    const settleRes = await getBaseList('settle_type') //付款方式
    const invoiceRes = await getBaseList('invoice_type ') //发票类型

    screenOptions.categoryList = cateRes.data
    screenOptions.transport_type = transportRes.data
    screenOptions.settle_type = settleRes.data
    screenOptions.invoice_type = invoiceRes.data

    categoryArray.value = await cateRes.data.map((item: any) => {
      return {
        ...item,
        value: item.uid,
        label: item.name,
      }
    })

    // 创建时抓取个人信息
    if (props.from_type != 'create') return
    loading.value = true
    //通过个人信息赋值买方信息
    const _userInfo = JSON.parse(userInfo.value)
    const { uid, user_name } = _userInfo
    const row: any = categoryArray.value.filter((item: any) => item.uid == uid)

    buyUid.value = uid
    baseForm.value.buyer_customer_id = uid

    await toBaseFrom(row[0])
    emit('switchBuyer', user_name)

    setTimeout(() => {
      loading.value = false
    }, 500)
  }

  // 获取省市区
  const _GetAreaOptions = async () => {
    arrdessOptions.value = await areaOptions()
  }

  // 获取更新数据
  const getUpdateData = (res: any) => {
    baseForm.value = {
      ...res,
      invoice_type: `${res.invoice_type || ''}`,
      pay_type: `${res.pay_type || ''}`,
      transport_type: `${res.transport_type || ''}`,
      shipping_address: res.shipping_address
        ? res.shipping_address.split(',')
        : [],
    }

    buyUid.value = res.buyer_customer_id
  }
  // 自定义筛选
  const handleCustomAdd = async (prop = '') => {
    if (prop == 'transport_type') {
      const transportRes = await getBaseList('transport_type') //运输方式
      screenOptions.transport_type = transportRes.data
    }
  }

  /**
   * @实例
   */

  onMounted(() => {
    _GetScreenOptions()
    _GetAreaOptions()
  })

  defineExpose({
    baseFormRef,
    baseForm,
    getUpdateData,
  })
</script>
<style lang="scss" scoped>
  .marb-20 {
    display: inline-block;
    margin-bottom: 20px;
  }
  .border {
    width: 100%;
    border: 1px solid rgba(192, 196, 204, 0.6);
    box-sizing: border-box;
    display: flex;
    flex-direction: column;
    justify-content: flex-end;
    border-radius: 5px;
    transition: var(--el-transition-box-shadow);
    transform: translate3d(0, 0, 0);
    padding: 4px;
    &:hover {
      border: 1px solid rgba(192, 196, 204, 0.8);
    }
    :deep() {
      .el-input__wrapper {
        box-shadow: none;
      }
      .el-input__wrapper:hover {
        box-shadow: none;
      }
    }
  }

  .searchfor {
    :deep() {
      .el-form-item {
        margin-bottom: 16px;
      }
    }
  }
</style>
../../tools
